package imoocvideodev.controller;

import imoocvideodev.common.result.IMoocJSONResult;
import imoocvideodev.common.result.PagedResult;
import imoocvideodev.common.result.VideoStatusEnum;
import imoocvideodev.common.util.videoUtil.FetchVideoCover;
import imoocvideodev.common.util.videoUtil.MergeVideoBgm;
import imoocvideodev.common.util.FileUtil;
import imoocvideodev.pojo.BGM;
import imoocvideodev.pojo.Comments;
import imoocvideodev.pojo.Videos;
import imoocvideodev.service.BgmService;
import imoocvideodev.service.VideoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * @Author: Redi
 * @Date: 2021/2/6 21:33
 * @Description: 视频控制器类
 */

@RestController
@Api(value = "视频相关业务的接口",tags = {"视频相关业务的controller"})
@RequestMapping("/video")
public class VideoController extends BasicController {

    //用户命名空间
    private static final String UPLOAD_PATH =  "D:/tmpCode/imooc-video-user-data";
    //ffmpeg 地址
    private static final String ffmpegEXE =  "D:/Linux/ffmpeg/ffmpeg/bin/ffmpeg.exe";
    @Autowired
    VideoService videoService;
    @Autowired
    BgmService bgmService;

    @ApiOperation(value = "用户上传视频",notes = "用户上传视频的接口")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "userId",value = "用户ID",required = true,dataType = "String", paramType = "form"),
        @ApiImplicitParam(name = "bgmId",value = "背景音乐ID",required = false,dataType = "String", paramType = "form"),
        @ApiImplicitParam(name = "videoSeconds",value = "视频时长",required = true,dataType = "float", paramType = "form"),
        @ApiImplicitParam(name = "videoWidth",value = "视频画面宽度",required = true,dataType = "int", paramType = "form"),
        @ApiImplicitParam(name = "videoHeight",value = "视频画面高度",required = true,dataType = "int", paramType = "form"),
        @ApiImplicitParam(name = "desc",value = "视频描述",required = false,dataType = "String", paramType = "form")
    })
    @PostMapping("/upload.do")
    public IMoocJSONResult upload(String userId,String bgmId,Float videoSeconds
                                  ,int videoWidth,int videoHeight,String desc,
                                  MultipartFile file) throws IOException {

        if (StringUtils.isBlank(userId)){
            return IMoocJSONResult.errorMsg("userId不能为空");
        }
        //无服务器前缀路径 uploadPathDB
        String uploadPathDB =  "/" + userId + "/video";
        String uploadCoverPathDB =  "/" + userId + "/video/cover/" + UUID.randomUUID().toString() + ".jpg";


        //绝对路径 videoAbsolutePath
        String videoAbsolutePath = null;
        //最终视频的输出路径
        String finalVideoPath = null;
        try{
            videoAbsolutePath = FileUtil.uploadFile(file,uploadPathDB);
            //返回的地址是经过MVC映射的，故只能返回 UPLOAD_PATH 后面的那一串字符。
            String[] returnImagePaths = videoAbsolutePath.split(UPLOAD_PATH);
            uploadPathDB = returnImagePaths[1];

            //截取并上传视频封面
            FetchVideoCover.fetchCover(videoAbsolutePath,UPLOAD_PATH+uploadCoverPathDB);
        }
        catch (Exception e){
            return IMoocJSONResult.errorMsg("上传出错");
        }
        //若bgmId不为空，查找bgmId对应的bgm，并合并音视频
        if (StringUtils.isNotBlank(bgmId)){
            BGM bgm = bgmService.getBgmById(bgmId);
            String bgmPath = UPLOAD_PATH + bgm.getPath();
            String videoInputPath = videoAbsolutePath;

            //找到上传文件的后缀名
            String suffix = videoInputPath.substring(videoInputPath.lastIndexOf(".") );

            finalVideoPath = UPLOAD_PATH + "/" + userId + "/video/" + UUID.randomUUID().toString() + suffix;

            MergeVideoBgm.mergeVideoAudio(videoInputPath,bgmPath,videoSeconds,finalVideoPath);

            String[] returnImagePaths = finalVideoPath.split(UPLOAD_PATH);
            uploadPathDB = returnImagePaths[1];
        }

        Videos insertVideos = new Videos();
        insertVideos.setId(UUID.randomUUID().toString());
        insertVideos.setUserId(userId);
        insertVideos.setAudioId(bgmId);
        insertVideos.setVideoDesc(desc);
        insertVideos.setVideoPath(uploadPathDB);
        insertVideos.setVideoSeconds(videoSeconds);
        insertVideos.setVideoWidth(videoWidth);
        insertVideos.setVideoHeight(videoHeight);
        insertVideos.setCoverPath(uploadCoverPathDB);
        insertVideos.setStatus(VideoStatusEnum.SUCCESS.value);
        insertVideos.setCreateTime(new Date());

        String videoId = videoService.insert(insertVideos);

        //分割后的字符串，第二串才是要返回的！
        return IMoocJSONResult.okData(videoId);
    }

    @ApiOperation(value = "上传视频封面",notes = "上传视频封面的接口")
    @ApiImplicitParam(name = "videoId",value = "视频ID",required = true,dataType = "String", paramType = "form")
    @PostMapping("/uploadCover.do")
    public IMoocJSONResult uploadCover(String videoId, String userId,
                                      @RequestParam("file") MultipartFile file) {

        if (file == null){
            return IMoocJSONResult.errorMsg("传入的coverFile为空！");
        }

        if (StringUtils.isAnyBlank(videoId,userId)){
            return IMoocJSONResult.errorMsg("videoId或userId为空");
        }

        //无服务器前缀路径 uploadPathDB
        String uploadPathDB =  "/" + userId + "/video/cover";

        //绝对路径 coverImagePath
        String coverImagePath = null;
        try{
            coverImagePath = FileUtil.uploadFile(file,uploadPathDB);

            //返回的地址是经过MVC映射的，故只能返回 UPLOAD_PATH 后面的那一串字符。
            String[] returnImagePaths = coverImagePath.split(UPLOAD_PATH);
            uploadPathDB = returnImagePaths[1];

            Videos updatedVideos = new Videos();
            updatedVideos.setId(videoId);
            updatedVideos.setCoverPath(uploadPathDB);
            videoService.update(updatedVideos);
        }
        catch (Exception e){
            return IMoocJSONResult.errorMsg("上传出错");
        }

        //分割后的字符串，第二串才是要返回的！
        return IMoocJSONResult.okData(uploadPathDB);
    }

    /**
     * @author Redi
     * @description 分页获取所有视频
     * @params video,isSaveRecord,page
     * isSaveRecord: 1 - 可以保存
     *               0 - 不保存
     * @return IMoocJSONResult
     * @date 2021/2/23
     */
    @PostMapping("/showAll.do")
    @ApiOperation(value = "分页获取所有视频",notes = "分页获取所有视频的接口")
    public IMoocJSONResult showAllVideos(@RequestBody Videos video, Integer isSaveRecord,
                                         @RequestParam(value = "page", defaultValue = "1") Integer page){

        PagedResult result = videoService.findAllVideos(video, isSaveRecord, page, PAGE_SIZE);
        return IMoocJSONResult.okData(result);
    }

    @PostMapping("/getHotWords.do")
    @ApiOperation(value = "获得热搜词",notes = "获得热搜词的接口")
    public IMoocJSONResult getHotWords(){
        return IMoocJSONResult.okData(videoService.getHotWords());
    }

    @PostMapping("/userLike.do")
    @ApiOperation(value = "用户点赞视频",notes = "用户点赞视频的接口")
    public IMoocJSONResult userLike(String userId, String videoId, String videoCreaterId){
        if (StringUtils.isAnyBlank(userId,videoCreaterId,videoId)){
            return IMoocJSONResult.errorMsg("传入的参数不可为空！");
        }
        return videoService.userLikeVideo(userId, videoId, videoCreaterId);
    }

    @PostMapping("/userUnLike.do")
    @ApiOperation(value = "用户取消点赞视频",notes = "用户取消点赞视频的接口")
    public IMoocJSONResult userUnLike(String userId, String videoId, String videoCreaterId){
        if (StringUtils.isAnyBlank(userId,videoCreaterId,videoId)){
            return IMoocJSONResult.errorMsg("传入的参数不可为空！");
        }
        return videoService.userUnLikeVideo(userId, videoId, videoCreaterId);
    }

    @PostMapping("/saveComment.do")
    @ApiOperation(value = "用户评论视频",notes = "用户评论视频的接口")
    public IMoocJSONResult saveComment(@RequestBody Comments comments,
                                       String fatherCommentId, String toUserId){
        comments.setFatherCommentId(fatherCommentId);
        comments.setToUserId(toUserId);
        return videoService.saveComment(comments);
    }

    @PostMapping("/getAllComments.do")
    @ApiOperation(value = "获取视频的所有用户评论",notes = "获取视频的所有用户评论的接口")
    public PagedResult getAllComments(String videoId,
                                      @RequestParam(value = "page",defaultValue = "1") Integer page,
                                      @RequestParam(value = "size",defaultValue = "5") Integer size){

        return videoService.getAllComments(videoId, page, size);
    }

}
